package wykop.download.proxy;

import java.io.ByteArrayInputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

import wykop.utils.Streams;
import wykop.utils.XmlUtils;

public class ProxyChecker implements IProxyChecker {

	@Override
	public boolean worksWith(final Proxy proxy, final String urlAsString) {

		try {
			final URL url = new URL(urlAsString);
			final HttpURLConnection connection = (HttpURLConnection) url
					.openConnection(proxy);
			connection.setRequestMethod("GET");
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(5000);
			connection.connect();

			final int status = connection.getResponseCode();

			if (status == HttpURLConnection.HTTP_OK) {
				final byte[] bytes = Streams.readFully(connection
						.getInputStream());
				XmlUtils.fromHtmlStream(new ByteArrayInputStream(bytes));
				return true;
			}

			return false;
		} catch (final Exception e) {
			return false;
		}
	}

}
